package userSql

import (
	"errors"
	"fmt"
	"ginchat/models/mysqlModel"
	"ginchat/models/requstModel"
	"ginchat/utils/gormInit"
	"gorm.io/gorm"
)

var Db = gormInit.Get()
//获取所有用户消息
func GetUserList() ([]mysqlModel.UserBasic,error){
	data := make([]mysqlModel.UserBasic,10)
	db := Db.Find(&data)
	if db.Error != nil{
		err := errors.New("GetUserList 执行失败！")
		return nil,err
	}
	return data,nil
}
//创建用户
func CreateUser(requstMode requstModel.CreateUserRequst,salt string) (mysqlModel.UserBasic,error){
	user := &mysqlModel.UserBasic{
		Name: requstMode.Name,
		Password: requstMode.Password,
		Phone: requstMode.Phone,
		Email: requstMode.Email,
		Salt: salt,
	}
	if db := Db.Create(user);db.Error != nil{
		return mysqlModel.UserBasic{},db.Error
	}
	return *user,nil
}

//删除用户
func DeleteUser(id int)error{
	user := mysqlModel.UserBasic{}
	db := Db.Where("id = ?",id).Delete(&user)
	if db.Error != nil{
		return db.Error
	}
	if db.RowsAffected == 0{
		err := errors.New("该用户不存在")
		return err
	}
	return nil
}

//修改用户
func  UpdateUser(requstMode requstModel.UpdateUserRequst)error{
	user := mysqlModel.UserBasic{
		Name: requstMode.Name,
		Password: requstMode.Password,
		Email: requstMode.Email,
		Phone: requstMode.Phone,
	}
	user.ID = uint(requstMode.Id)
	db := Db.Save(&user)
	if db.Error != nil{
		return db.Error
	}
	return nil
}

func FindUserByNameAndPassword(name,password string) (mysqlModel.UserBasic,error){
	user := mysqlModel.UserBasic{}
	db := Db.Where("name = ? and password = ?",name,password).First(&user)
	return user,db.Error
}

func NewToken(user *mysqlModel.UserBasic,token string) error{
	db := Db.Model(&mysqlModel.UserBasic{}).Where("id = ?",user.ID).Update("identity = ?",token)
	if db.Error != nil{
		return db.Error
	}
	return nil
}

func FindUserByName(name string) (mysqlModel.UserBasic,error) {
	user := mysqlModel.UserBasic{}
	db := Db.Where("name = ?",name).First(&user)
	return user,db.Error
}
func FindUserByEmail(email string) (mysqlModel.UserBasic,error){
	user := mysqlModel.UserBasic{}
	db := Db.Where("email = ?",email).First(&user)
	return user,db.Error
}
func FindUserByPhone(phone string) (mysqlModel.UserBasic,error){
	user := mysqlModel.UserBasic{}
	db := Db.Where("phone = ?",phone).First(&user)
	return user,db.Error
}

func SearchFriend(userId uint) []mysqlModel.UserBasic{
	contacts := make([]mysqlModel.Contact,0)
	objIds := make([]uint,0)
	users := make([]mysqlModel.UserBasic,0)
	Db.Where("owner_id = ? and type = 1",userId).Find(&contacts)
	for _,value := range contacts{
		fmt.Println(value)
		objIds = append(objIds,value.TargetId)
	}
	Db.Where("id in ?",objIds).Find(&users)
	return users
}

func AddFriend(userId uint,targetId uint) (int,string){
	user := &mysqlModel.UserBasic{}
	if targetId != 0{
		if targetId == userId{
			return 1,"不能添加自己"
		}
		contact0 := mysqlModel.Contact{}
		if db := Db.Where("onwer_id = ? and target_id = ? and type=1",userId,targetId).Find(&contact0);db.Error == nil{
			return 1,"不能重复添加好友"
		}

		db := Db.Where("id = ?",targetId).First(&user)
		if db.Error != nil{
			return 1,"该用户不存在"
		}
		tx := Db.Begin()
		//事务一旦开始，发生什么错误都会回滚
		defer func(){
			var a any
			r := recover()
			if r == a{
				tx.Rollback()
			}
		}()
		contact := mysqlModel.Contact{}
		contact.OwnerId  = userId
		contact.TargetId = targetId
		contact.Type = 1
		if db := tx.Create(&contact);db.Error != nil{
			tx.Rollback()
			return 1,"添加好友失败"
		}
		contact = mysqlModel.Contact{}
		contact.OwnerId  = targetId
		contact.TargetId = userId
		contact.Type = 1
		fmt.Println(contact)
		if db := tx.Create(&contact);db.Error != nil{
			tx.Rollback()
			return 1,"添加好友失败 "
		}
		tx.Commit()
		return 0,"添加好友成功"
	}
	return 1,"好友id不能为空"
}

func CreateCommunity(community mysqlModel.Community) (int,string){
	if community.Name == ""{
		return -1,"群名称不能为空"
	}
	if community.OwnerId == 0{
		return -1,"请先登录"
	}
	if err := Db.Create(&community).Error;err != nil{
		return -1,"创建失败"
	}
	return 0,"创建成功"
}

func LoadCommunity(owner_id uint)(error,[]mysqlModel.Community){
	communitys := []mysqlModel.Community{}
	db := Db.Where("owner_id = ?",owner_id).Find(&communitys)
	if db.Error != nil{
		if db.Error == gorm.ErrRecordNotFound{
			return nil,communitys
		}else{
			return db.Error,communitys
		}
	}
	return nil,communitys
}
func JoinGroup(contact mysqlModel.Contact,)(int,string){
	community := mysqlModel.Community{}
	Db.Where("id = ? or name = ?",contact.TargetId,contact.TargetId).Find(&community)
	if community.Name == ""{
		return -1,"没有找到群"
	}
	contact1 := mysqlModel.Contact{}
	Db.Where("owner_id = ? and target_id = ? and type = 2",contact.OwnerId,contact.TargetId).Find(&contact1)
	if !contact1.CreatedAt.IsZero(){
		return -1,"已加过这个群"
	}else{
		Db.Create(&contact)
		return 0,"加群成功"
	}

}

func SearchUserByGroupId(communityId uint) []uint {
	contacts := make([]mysqlModel.Contact, 0)
	objIds := make([]uint, 0)
	Db.Where("target_id = ? and type=2", communityId).Find(&contacts)
	for _, v := range contacts {
		objIds = append(objIds, uint(v.OwnerId))
	}
	return objIds
}